package shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import common.dto.PageResult;
import common.dto.shopdto.ShopCard;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import common.model.shop.Shop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import shop.mapper.ShopMapper;
import shop.service.IShopService;
import common.dto.shopdto.ShopDTO;

import java.util.List;
import org.springframework.data.redis.core.StringRedisTemplate;
import common.utils.RedisConstants;

import java.util.concurrent.TimeUnit;
import org.springframework.beans.BeanUtils;

import java.util.stream.Collectors;

import common.utils.CacheUtil;

@Service
public class ShopServiceImpl implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheUtil cacheUtil;

    //前台部分
    @Override
    public Result findById(Long id) {
        ShopDTO shopDTO = getShopDTOById(id);
        return Result.success(shopDTO);
    }
    //获取商铺并建立缓存
    public ShopDTO getShopDTOById(Long id) {
        String key = RedisConstants.SHOP_DETAIL_KEY + id;
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        
        return cacheUtil.getWithCache(
            key,
            ShopDTO.class,
            () -> {
                Shop shop = shopMapper.selectById(id);
                if (shop == null) {
                    return null;
                }
                ShopDTO shopDTO = new ShopDTO();
                BeanUtils.copyProperties(shop, shopDTO);
                return shopDTO;
            },
            lockKey,
            RedisConstants.SHOP_DETAIL_TTL,
            TimeUnit.MINUTES
        );
    }
    
    public Result getShopCard(Long id) {
        //查询商铺
        Shop shop = shopMapper.selectById(id);
        if(shop == null) {
            return Result.failure(ResultCodeEnum.FAIL,"商铺不存在");
        }
        //转化为ShopCard
        ShopCard shopCart = new ShopCard();
        shopCart.setId(shop.getId());
        shopCart.setImage(shop.getImage());
        shopCart.setName(shop.getName());
        shopCart.setScore(shop.getScore());
        shopCart.setTypeId(shop.getTypeId());

        return Result.success(shopCart);
    }

    //查询当前登录用户是否有商铺
    @Override
    public Result hasShop(Long uid) {
        //根据用户id查询商铺
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getUserId, uid);
        Shop shop = shopMapper.selectOne(queryWrapper);
        if(shop == null) {
            return Result.success(false);
        }
        return Result.success(true);
    }




    //后台部分
    @Override
    public Result getShopList(int page, int size) {
        // 分页查询
        Page<Shop> pageShops = new Page<>(page, size);
        // 构建查询条件
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Shop::getCreateTime);
        // 执行分页查询
        Page<Shop> pageResult = shopMapper.selectPage(pageShops, queryWrapper);
        // 将Shop对象转换为ShopDTO对象
        List<ShopDTO> shopDTOs = pageResult.getRecords().stream()
            .map(shop -> {
                ShopDTO shopDTO = new ShopDTO();
                BeanUtils.copyProperties(shop, shopDTO);
                return shopDTO;
            })
            .collect(Collectors.toList());
        // 返回结果
        return Result.success(shopDTOs);
    } 
    @Override
    public Result addShop(Shop shop) {
        shop.setId(null);
        shopMapper.insert(shop);
        return Result.success("商铺添加成功");
    }
    @Override
    public Result updateShop(Shop shop) {
        if (shop == null || shop.getId() == null) {
            return Result.failure(ResultCodeEnum.FAIL, "商铺ID不能为空");
        }
        shopMapper.updateById(shop);
        return Result.success("商铺修改成功");
    }
    @Override
    public Result deleteShop(Long id) {
        shopMapper.deleteById(id);
        return Result.success("商铺删除成功");
    }

}